import faces from '@/assets/js/face'
const escapeHtml = (content = '') => {
  if (!content) {
    return ''
  }
  let result = content

  // 替换表情
  const face = /\sface\[\S{1,}\]/g
  if (face.test(result)) {
    const group = result.match(face)
    group.forEach(item => {
      const key = item.match(/\[\S+\]/g)[0]
      result = result.replace(item, `<img src="${faces[key]}"/>`)
    })
  }
  // 替换图片 \S 查找非空白字符
  const img = /\simg\[\S+\]/g
  if (img.test(result)) {
    const group = result.match(img)
    group.forEach(item => {
      let src = item.match(/\[\S+\]/g)[0]
      src = src.substr(1, src.length - 2)
      result = result.replace(item, `<img src="${src}"/>`)
    })
  }
  // 替换链接 a(链接)[标题]
  const link = /\sa\(\S+\]/g
  if (link.test(result)) {
    const group = result.match(link)
    const title = /\((.+)\)/
    const linkName = /\[(.+)\]/
    group.forEach(item => {
      const nameGroup = item.match(linkName)
      let name = ''
      if (nameGroup && nameGroup.length) {
        name = nameGroup[1]
      }
      const linkGroup = item.match(title)
      let link = ''
      if (linkGroup && linkGroup.length) {
        link = linkGroup[1]
      }
      result = result.replace(item, `<a href="${link}">${name}</a>`)
    })
  }
  // 替换引用
  result = result.replace(/\[quote\]/g, '<div class="layui-elem-quote">')
  result = result.replace(/\[\/quote\]/g, '</div>')
  // 替换代码块
  result = result.replace(/\[pre\]/g, '<pre class="layui-code">')
  result = result.replace(/\[\/pre\]/g, '</pre>')
  // 替换hr
  result = result.replace(/\[hr]/g, '<hr/>')
  return result
}

export {
  escapeHtml
}
